<?php

namespace App\Http\Controllers\Home;

use App\Models\RechargeRecord;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Rules\CheckMobile;
use App\Rules\SecuriytCode;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    	$user_id = Auth::id();
    	$user = \App\Models\User::find($user_id);
    	
    	$profiles['gender'] = $user->getGender();
    	$profiles['address'] = $user->getAddress();
    	$profiles['industry'] = $user->getIndustry();
    	
    	return view('home/home',['profiles'=>$profiles]);
    }

    /**
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * 验证绑定手机号码
     */
    public function verifyMobile(Request $request)
    {
        if ($request->isMethod('get'))
            return view('home.telRevise1');

        $user = Auth::user();
        $mobile = $request->input('telephone');

        $message = [
            'captcha.required' => '请输入验证码',
            'captcha.captcha' => '验证码错误',
            'telephone.required' => '请输入手机号码',
            'telephone.notIn' => '所输入号码已被绑定',
            'telephone.exists' => '所输入号码与用户名不匹配'
        ];

        $validator = Validator::make($request->all(), [
                'captcha' => 'required|captcha',
                'telephone' => ['required', new CheckMobile(),
                    Rule::exists('users')->where(function ($query) use($user) {
                        $query->where('name', $user->name);
                    })
                ],
                'securiytCode' => ['required',new SecuriytCode($mobile)]
            ], $message);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $request->session()->put('verifyMobile', 'success');

        return redirect()->route('reviseMobile.revise');
    }

    /**
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * 验证新手机号码
     */
    public function reviseMobile(Request $request)
    {
        $verifyMobile = $request->session()->get('verifyMobile');

        if ($verifyMobile != 'success')
            return redirect()->route('reviseMobile.verify');

        if ($request->isMethod('get'))
            return view('home.telRevise2');

        $data = $request->all();
        $mobile = $request->input('telephone');

        $message = [
            'captcha.required' => '请输入验证码',
            'captcha.captcha' => '验证码错误',
            'telephone.required' => '请输入手机号码'
        ];

        $validator = Validator::make($data, [
            'captcha' => 'required|captcha',
            'telephone' => ['required', new CheckMobile(),
                Rule::notIn(['telephone'])
            ],
        ], $message);

        if ($validator->fails())
            return redirect()->back()->withErrors($validator)->withInput();

        $isExists = User::select('id', 'telephone')->where('telephone', $data['telephone'])->first();
        if ($isExists)
            return redirect()->back()->withErrors(['telephone' => '所输入号码已被绑定'])->withInput();

        $validator = Validator::make($data, [
            'securiytCode' => ['required',new SecuriytCode($mobile)]
        ]);

        if ($validator->fails())
            return redirect()->back()->withErrors($validator)->withInput();

        $user = Auth::user();
        $user->telephone = $data['telephone'];
        $user->save();

        $request->session()->forget('verifyMobile');
        $request->session()->flash('reviseDone', 'success');

        return redirect()->route('reviseMobile.done');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * 完成绑定手机修改
     */
    public function getReviseDone(Request $request)
    {
        $reviseDone = $request->session()->get('reviseDone');
        if ($reviseDone != 'success')
            return redirect()->route('reviseMobile.verify');

        return view('home.telRevise3');
    }

    /**
     * @desc 设置用户资料
     * @param Request $request
     */
    public function setUserProfiles(Request $request)
    {
    	$profiles_data = $request->all();
    	$address = [
    			'province'=>$profiles_data['province'],
    			'city' =>$profiles_data['city'],
    			'district'=>$profiles_data['district'],
    			'street' =>$profiles_data['street']
    	];
    	
    	$industry = [
    			'industry1' =>$profiles_data['industry1'],
    			'industry2' =>$profiles_data['industry2'],
    	];
    	
    	$user_id = Auth::id();
    	$user = \App\Models\User::find($user_id);
    	
    	$user->setGender($profiles_data['sex']);
    	$user->setAddress($address);
    	$user->setIndustry($industry);
    	
    	if($user->save())
    	{
    		return response()->json([
    				'error_code'=> 0,
    				'message' =>'success',
    				'data'=>[]
    		]);
    	}else{
    		return Redirect::back()->withInput()->withErrors('保存失败！');
    	}
    }
    
    /**
     * @desc 用户管理中心余额列表
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function recharge()
    {
    	$user_id = Auth::id();
    	$list = RechargeRecord::where([['user_id','=',$user_id],['status','=','success']])
            ->orderBy('id', 'DESC')
            ->paginate(15);
    	
    	$user = \App\Models\User::find($user_id);
    	
    	return view('home/recharge', ['recharge'=>$list,'user_coin'=>$user->coin]);
    }
    
    
    /**
     * @desc 支付宝付款页面
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function payment()
    {
    	$recharge_templets_list = \App\Models\RechargeTemplets::where('status','enabled')->get();
    	$recharge_limit = \App\Models\PayConfig::where('id', 1)->first();
    	
    	return view('home/payment',['recharge_templets_list'=>$recharge_templets_list,'recharge_limit'=>$recharge_limit]);
    }
    
    
    /**
     * @desc 付款成功页面
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function paymentSuccess()
    {
    	return view('home/payment_success');
    }
}
